﻿using OA.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using OA.BLL;
using OA.Web.Areas.Member.Controllers;
using Z.EntityFramework.Plus;
using OA.Model.View;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Http;
using OA.Web.Code;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;

namespace OA.Web.Areas.Management.Controllers
{
    [Area("Management")]
    public class DepartmentController : BaseMemberController
    {

        private IMemoryCache _cache;
        public DepartmentController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        [HttpGet]
        [MyActionFilter("205001", "部门管理", "人力资源管理", true, "iconbumen2")]
        public IActionResult Index(string keyword)
        {
            ViewBag.Keyword = keyword;
            return View();
        }

        [HttpGet]
        [MyActionFilter("205001", "部门管理")]
        public IActionResult GetData(string keyWord, int page = 1, int limit = 12)
        {
            Expression<Func<VDepartment, bool>> where = m => true;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = m => m.Name.Contains(keyWord);
            }
            var listAll = this.dbContextFactory.DbContext.VDepartment.Where(where).OrderBy(m=>m.ID).ToList();
            foreach (var item in listAll)
            {
                item.FullName = CDepartment.GetFullDepartmentNameByID(item.ID, listAll.Select(m => new Department() { ID = m.ID, Name = m.Name, ParentDepartmentID = m.ParentDepartmentID }).ToList());
            }
            

            var result = new
            {
                code = "0",
                msg = "",
                count = listAll.Count,
                data = listAll.Skip((page-1)*limit).Take(limit)
            };
            return Json(result);
        }

        [HttpGet]
        [MyActionFilter("205001001", "添加部门", "部门管理",false,"")]
        public IActionResult Create(int departmentID = 0)
        {
            if (departmentID == 0)
            {
                departmentID = this.dbContextFactory.DbContext.Department.Where(m => m.ParentDepartmentID == 0).Select(m => m.ID).FirstOrDefault();
            }
            return View(new Department() { ParentDepartmentID= departmentID });
        }

        [HttpPost]
        [MyActionFilter("205001001", "添加部门", "部门管理", false, "")]
        public IActionResult Create(int[] department, int sort,string name)
        {
            BaseResult baseResult = new BaseResult();
            Department info = new Department();
            info.Name = name;
            info.Sort = sort;

            if (department == null|| department.Length==0)
            {
                baseResult.State = 400;
                baseResult.Msg = "请选择一个上级部门";
                return Json(baseResult); 
            }
            department = department.Where(m => m > 0).ToArray();            
            if (department.Length == 0)
            {
                info.ParentDepartmentID = 0;
            }
            else
            {
                info.ParentDepartmentID = department[department.Length - 1];
                Department parent = this.GetInfo<Department>(info.ParentDepartmentID);
                if (parent == null)
                {
                    baseResult.State = 400;
                    baseResult.Msg = "您选择一个非法的上级部门";
                    return Json(baseResult);
                    
                }               
            }
            if (string.IsNullOrWhiteSpace(info.Name))
            {
                baseResult.State = 400;
                baseResult.Msg = "部门名称不能为空";
                return Json(baseResult);
                
            }
            info.Status = 1;
            this.AddInfo<Department>(info);
            baseResult.Msg = "部门添加成功";
            return Json(baseResult);
        }

        [MyActionFilter("205001002", "管理排序", "部门管理", false, "")]
        public IActionResult SetSort(int id, int sort)
        {             
            try
            {
                Department infoDepartment = this.GetInfo<Department>(id);
                if (infoDepartment == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Department updateDepartment = new Department();
                updateDepartment.Sort = sort;
                this.Update<Department>(infoDepartment, updateDepartment, new string[] { "Sort" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [MyActionFilter("205001003", "启用部门", "部门管理", false, "")]
        public IActionResult Enabled(int id)
        {
            try
            {
                Department infoDepartment = this.GetInfo<Department>(id);
                if (infoDepartment == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Department updateDepartment = new Department();
                updateDepartment.Status = 1;
                this.Update<Department>(infoDepartment, updateDepartment, new string[] { "Status" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [MyActionFilter("205001004", "修改部门名称", "部门管理", false, "")]
        public IActionResult SetName(int id, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return Json(new { State = 400, Message = "部门名称不能为空" });
            }
            try
            {
                Department infoDepartment = this.GetInfo<Department>(id);
                if (infoDepartment == null)
                {
                    return Json(new { State = 400, Message = "没有找到相关的记录" });
                }
                Department updateDepartment = new Department();
                updateDepartment.Name = name;
                this.Update<Department>(infoDepartment, updateDepartment, new string[] { "Name" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [HttpGet]
        [MyActionFilter("205001005", "删除部门", "部门管理", false, "")]
        public IActionResult Delete(int id)
        {
            try
            {
                var list = this.dbContextFactory.DbContext.Department.Select(m => new SimpleDepartment2 { ID = m.ID, ParentDepartmentID = m.ParentDepartmentID }).ToList();
                var department = list.Where(m => m.ID == id).FirstOrDefault();
                if (department == null)
                {
                    return Json(new { State = 400, Message = "，没有当前该部门" });
                }
                List<int> ids = new List<int>();
                ids.Add(id);
                List<SimpleDepartment2> children = list.Where(m => m.ParentDepartmentID == id).ToList();
                while (children.Count > 0)
                {
                    List<SimpleDepartment2> children2_all = new List<SimpleDepartment2>();
                    foreach (var item in children)
                    {
                        ids.Add(item.ID);
                        List<SimpleDepartment2> children2 = list.Where(m => m.ParentDepartmentID == item.ID).ToList();
                        children2_all = children2_all.Union(children2).ToList();
                    }
                    children = children2_all;
                }

                Expression<Func<Department, bool>> where = m => ids.Contains(m.ID);
                Department updateDepartment = new Department();
                updateDepartment.Status = -1;
                this.UpdateByWhere<Department>(where, updateDepartment, new string[] { "Status" });
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }

        [HttpGet]
        [MyActionFilter("205001006", "查看部门树形图", "部门管理", false, "")]
        public IActionResult ShowTree()
        {
            List<Department> list = this.dbContextFactory.DbContext.Department.Where(m => m.Status != -1).ToList();             
            ViewBag.Results = JsonConvert.SerializeObject(list.Select(m => new { id = m.ID.ToString(), isroot = m.ParentDepartmentID == 0, topic = m.Name, parentid = m.ParentDepartmentID.ToString() }));
            return View();
        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <param name="id"></param>
        /// <param name="parentID"></param>
        /// <returns></returns>
        [HttpGet]
        [MyActionFilter("205001007", "移除管理", "部门管理", false, "")]
        public IActionResult Remove(int id,int parentID)
        {
            try
            {
                var list = this.dbContextFactory.DbContext.Department.ToList();
                var department = list.Where(m => m.ID == id).FirstOrDefault();
                var parentDepartment = list.Where(m => m.ID == parentID).FirstOrDefault();                
                if (department == null)
                {
                    return Json(new { State = 400, Message = "，没有当前该部门" });
                }
                Dictionary<Department, Department> dicUpdate = new Dictionary<Department, Department>();
                Dictionary<int, Department> dicDepartment = new Dictionary<int, Department>();

                Department updateDepartment = new Department();
                updateDepartment.ParentDepartmentID = parentID;
                updateDepartment.ID = id;
                updateDepartment.FullName = parentDepartment.FullName + " " + department.Name;

                dicUpdate.Add(department,updateDepartment);
                dicDepartment.Add(id, updateDepartment);
                string parentFullName = updateDepartment.FullName;
                List<Department> children = list.Where(m => m.ParentDepartmentID == id).ToList();
                while (children.Count > 0)
                {                    
                    foreach (var item in children)
                    {
                        List<Department> children2_all = new List<Department>();
                        if (dicDepartment.ContainsKey(item.ParentDepartmentID))
                        {
                            Department parent = dicDepartment[item.ParentDepartmentID];
                            Department updateItem = new Department();
                            updateItem.ID = item.ID;
                            updateItem.ParentDepartmentID = item.ParentDepartmentID;
                            updateItem.FullName = parent.FullName + " " + item.Name;
                            dicUpdate.Add(item, updateItem);
                            dicDepartment.Add(updateItem.ID, updateItem);
                            List<Department> children2 = list.Where(m => m.ParentDepartmentID == item.ID).ToList();
                            children2_all = children2_all.Union(children2).ToList();
                        }
                        children = children2_all;
                    }                    
                }

                using (var trn = this.dbContextFactory.DbContext.Database.BeginTransaction())
                {
                    try
                    {
                        foreach (Department item in dicUpdate.Keys)
                        {
                            this.Update<Department>(item, dicUpdate[item], new string[] { "ParentDepartmentID", "FullName" });
                        }
                        trn.Commit();
                    }
                    catch(Exception ex2)
                    {
                        trn.Rollback();
                        return Json(new { State = 400, Message = "数据库操作异常,请稍后重试" });
                    }
                }                    
                return Json(new { State = 200, Message = "" });

            }
            catch (Exception ex)
            {
                return Json(new { State = 400, Message = "系统异常,请稍后重试" });
            }
        }


        [HttpGet]
        [MyActionFilter("205001008", "设置部门领导", "部门管理", false, "")]
        public IActionResult SetLeaderPositionID(int id)
        {
            Department infoDepartment = this.dbContextFactory.DbContext.Department.Where(m => m.ID == id).FirstOrDefault();
            if (infoDepartment == null)
            {
                ViewBag.ErrorMsg = "系统中没有找到该部门信息";
            }
            else
            {
                var positions = this.dbContextFactory.DbContext.Position.Where(m => m.DepartmentID == id && m.Status != -1).ToList();
                if(positions.Count==0)
                {
                    ViewBag.ErrorMsg = "当前部门下没有找到任何岗位信息";
                }
                ViewBag.Positions = positions;
            }
            return View(infoDepartment);
        }


        [HttpPost]
        [MyActionFilter("205001008", "设置部门管理岗位", "部门管理", false, "")]
        public IActionResult SetLeaderPositionID(int id,int positionID,int LeaderPositionID2)
        {
            
            Department infoDepartment = this.dbContextFactory.DbContext.Department.Where(m => m.ID == id).FirstOrDefault();
            if (infoDepartment == null)
            {
                ViewBag.ErrorMsg = "系统中没有找到该部门信息";
            }
            else
            {
                if (positionID>0)
                {
                    var position = this.dbContextFactory.DbContext.Position.Where(m => m.ID == positionID).FirstOrDefault();
                    if (position == null || position.Status == -1)
                    {
                        ViewBag.ErrorMsg = "岗位信息不存在";
                    }
                    else if(position.DepartmentID!=id)
                    {
                        ViewBag.ErrorMsg = "当前岗位不属于当前部门";
                    }
                    else
                    {
                        this.dbContextFactory.DbContext.Department.Where(m => m.ID == id).Update(m => new Department() { LeaderPositionID = positionID, LeaderPositionID2= LeaderPositionID2 });
                    }
                }
                else
                {
                    this.dbContextFactory.DbContext.Department.Where(m => m.ID == id).Update(m => new Department() { LeaderPositionID = 0, LeaderPositionID2 = LeaderPositionID2 });
                }
            }
            return Content($"<script>window.parent.FinshOther('部门负责人设置成功');</script>", "text/html");
        }
    }
}